package com.ruoyi.stock.service.impl.test;

import okhttp3.*;
import com.google.gson.Gson;
import java.io.IOException;

public class LonghuDataProcessor {

    private final OkHttpClient client;
    private final Gson gson;

    public LonghuDataProcessor() {
        this.client = new OkHttpClient();
        this.gson = new Gson();
    }

    // 获取并解析数据
    public LonghuResponse fetchData(String url) {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String jsonString = response.body().string();
                // 使用 Gson 将 JSON 字符串转换为 Java 对象
                return gson.fromJson(jsonString, LonghuResponse.class);

            } else {
                System.out.println("请求失败! 状态码: " + response.code());
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 获取并解析数据
    public LonghuResponse fetchHistoryData(String url) {
        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                .addHeader("Accept", "*/*")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String jsonString = response.body().string();
                // 使用 Gson 将 JSON 字符串转换为 Java 对象
                return gson.fromJson(jsonString, LonghuResponse.class);

            } else {
                System.out.println("请求失败! 状态码: " + response.code());
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}